﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Vav.Data.TransferTypes;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Text;
using System.Web;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace Vav.Data.Utils
{
    public static class MobileHelper
    {
        public static bool IsMobileNum(this string num)
        {
            String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
            return System.Text.RegularExpressions.Regex.IsMatch(num, regex);
        }

        public static string MobileCreateCode()
        {
            //return ((int)Math.Floor(new Random().NextDouble() * 1000000)).ToString().PadLeft('0').Trim();
            return new Random().Next(100000, 999999).ToString();

        }

        //发送语音验证码
        public static Tuple<int, string> SendVsmsCode(string mobile, string code)
        {
            var appKey = "8c13dd8be6ceeaa36688fffbffd6d1f7";
            var appSecret = "48211dc5f133";
            var curTime = getCurrentTime().ToString();
            var nonce = getRandom().ToString();
            //var code = getCode();
            var checkSum = getCheckSum(appSecret, nonce, curTime);
            var parameters = new Dictionary<string, string>();
            parameters.Add("mobile", mobile);
            parameters.Add("templateid", "9514316");
            parameters.Add("authCode", code);
            var result = SendRequest(parameters, appKey, nonce, curTime, checkSum);

            return new Tuple<int, string>(1, result);

        }

        public static SmsResponse SendSms(string mobile, string code, SmsType smsType)
        {
            var content = GetSmsContent(smsType);
            content = content.Replace("{code}", code);
            var un = "YZM6551777";// 
            var pwd = "Z2hcmstUNpcd5a"; //
            var postJsonTpl = "\"account\":\"{0}\",\"password\":\"{1}\",\"phone\":\"{2}\",\"report\":\"false\",\"msg\":\"{3}\"";
            string jsonBody = string.Format(postJsonTpl, un, pwd, mobile, content);
            return SmsDoPostMethodToObj("{" + jsonBody + "}");
        }
        private static SmsResponse SmsDoPostMethodToObj(string jsonBody)
        {
            string result = String.Empty;

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://smssh1.253.com/msg/send/json");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            // Create NetworkCredential Object 
            NetworkCredential admin_auth = new NetworkCredential("username", "password");

            // Set your HTTP credentials in your request header
            httpWebRequest.Credentials = admin_auth;

            // callback for handling server certificates
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonBody);
                streamWriter.Flush();
                streamWriter.Close();
                HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            return result.ToObject<SmsResponse>();
        }


        private static string GetSmsContent(SmsType smsType)
        {
            var result = "";
            if (smsType == SmsType.Register)
            {
                result = "尊敬的用户，您在{titlename}的验证码为：{code}。";
            }
            else if (smsType == SmsType.ForgetPwd)
            {
                result = "尊敬的用户，您在{titlename}使用了重置密码功能,您的密码为：{code}。";
            }
            else
            {
                result = "尊敬的用户，您的手机验证码为：{code}。";
            }
            return result;
        }


        //request
        private static string SendRequest(IDictionary<string, string> parameters, string appKey, string Nonce, string CurTime, string CheckSum)
        {

            HttpWebRequest req = null;
            HttpWebResponse rsp = null;
            System.IO.Stream reqStream = null;
            try
            {
                req = (HttpWebRequest)WebRequest.Create("https://api.netease.im/sms/sendcode.action");
                req.Method = "POST";
                req.KeepAlive = false;
                req.ProtocolVersion = HttpVersion.Version10;
                req.Timeout = 15000;
                req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                req.Headers.Add("AppKey", appKey);
                req.Headers.Add("Nonce", Nonce);
                req.Headers.Add("CurTime", CurTime);
                req.Headers.Add("CheckSum", CheckSum);
                byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                rsp = (HttpWebResponse)req.GetResponse();
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                if (reqStream != null) reqStream.Close();
                if (rsp != null) rsp.Close();
            }

        }

        //获取时间戳
        private static long getCurrentTime()
        {
            return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        }
        //获取验证码
        private static string getCode()
        {
            return (new Random().Next(100000, 999999)).ToString();
        }
        //获取随机数
        private static long getRandom()
        {
            return (new Random((int)getCurrentTime())).Next() % 900000L + 100000L;
        }
        //获取sign
        private static String getCheckSum(String appSecret, String nonce, String curTime)
        {
            return Sha1Sign(appSecret + nonce + curTime, Encoding.UTF8);
        }
        //哈希加密
        private static String Sha1Sign(String content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();//创建SHA1对象
                byte[] bytes_in = encode.GetBytes(content);//将待加密字符串转为byte类型
                byte[] bytes_out = sha1.ComputeHash(bytes_in);//Hash运算
                sha1.Dispose();//释放当前实例使用的所有资源
                String result = BitConverter.ToString(bytes_out);//将运算结果转为string类型
                result = result.Replace("-", "").ToLower();//替换并转为小写
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        // 组装普通文本请求参数。    
        static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }
        // 把响应流转换为文本。   
        static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }
        public static string GetEncryptionMobelPhone(this string phone)
        {
            try
            {
                return Regex.Replace(phone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            }
            catch (Exception)
            {
                return "未知号码";
            }

        }
    }
}
